﻿using Microsoft.AspNetCore.Mvc;
using StudentMaragement.Models;
using StudentMaragement.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace StudentMaragement.Controllers
{
    
    public class HomeController : Controller
    {
       
        //readonly 防止不小心设置为空
        public readonly IStudentRepository _studentRepository;

        /// <summary>
        /// 使用构造函数的方式注入IStudentRepository
        /// </summary>
        public HomeController(IStudentRepository studentRepository)
        {
            _studentRepository = studentRepository;
        }

        public IActionResult Details(int? id)
        {
            /*Student stu = _studentRepository.GetStudent(1);
            return View(stu);*/
            //实例化并存储Student信息和PageTitle
            HomeDetailsViewModel homeDetailsViewModel = new HomeDetailsViewModel()
            {
                Student = _studentRepository.GetStudent(id??1),
                PageTitle = "学生详情"
            };
            return View(homeDetailsViewModel);
        }



        public  IActionResult Index()

        {
           var students = _studentRepository.GetAllStudents();
            return View(students);

        }


        //添加数据
        [HttpGet]
        public IActionResult Create()
        {
            return View();

        }
        //接收前端传过来的表单信息，并绑定到模型
        [HttpPost]
        public IActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            {
                Student newStudent = _studentRepository.Add(student);

                return RedirectToAction("Details", new { id = newStudent.Id });

            }
            return View();
            
           
        }
    }
}
